package com.naiterui.ehp.bs.patient.controller;

import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.domain.Patient;
import com.naiterui.ehp.bp.support.context.ResourceHolder;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.security.SettingConfig;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.service.IPatientCaseFileService;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.utils.ParamsUtil;
import com.naiterui.ehp.bs.patient.utils.constants.PatientConstant;
import com.naiterui.ehp.bs.patient.vo.casefile.CaseDetailVO;
import com.naiterui.ehp.bs.patient.vo.casefile.CaseImgVO;
import com.naiterui.ehp.bs.patient.vo.casefile.CaseListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者病历档案业务控制器 <P>File name : PatientCaseController.java </P> <P>Author :
 * NTR.Amber </P> <P>Date : 2015年9月13日 </P>
 */
@Api(tags = SwaggerTag.PATIENT + SwaggerTag.PATIENT_CASE)
@RequestMapping("ap/patient/case")
@Controller
public class ApPatientCaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApPatientCaseController.class);

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IPatientCaseFileService patientCaseFileService;

    /**
     * 分页获取个人病历档案 PatientCaseController.getCaseFileList()<BR> <P>Author : Amber
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("list")
    @ApiOperation(value = "病例档案列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public PageVO<CaseListVO> getCaseFileList(Long patientId, PageParamVO pageParamVO) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        // 参数错误，记录日志
        if (patientId == null) {
            LOGGER.error("patient case list ERROR ; illegal param : patientId is null,page {},num{}", pageParamVO.getPage(),
                         pageParamVO.getNum());
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        Patient patient = this.patientService.getPatient(patientId);
        // 患者用户不存在
        if (patient == null) {
            LOGGER.error("patient case list ERROR ; patient not exist. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        // 患者被禁用
        if (patient.getAccountStatus() != 0) {
            LOGGER.error("patient case list ERROR ; patient account status wrong. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_ACCOUNT_ERROR);
        }

        // 分页获取结果集
        PageVO<CaseListVO> caseList = this.patientCaseFileService.getCaseFileList(patientId, pageParamVO.getPage(), pageParamVO.getNum());
        // 记录请求日志，日志级别info
        LOGGER.info("patient case list SUCCESS ; patientId {},page {},num {}", patientId, pageParamVO.getPage(), pageParamVO.getNum());
        return caseList;
    }

    /**
     * 查看患者某病例档案详情。 PatientCaseController.getCaseFileDetail()<BR> <P>Author :
     * Amber </P> <P>Date : 2015年9月13日 </P>
     *
     * @param patientId
     * @param caseId
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("detail")
    @ApiOperation(value = "病历档案详情", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public CaseDetailVO getCaseFileDetail(Long patientId, String caseId) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        // 参数异常
        if (patientId == null || StringUtils.isBlank(caseId)) {
            // 日志记录参数信息
            LOGGER.error("patient case detail ERROR ; illegal param : patientId {},caseId {}", patientId, caseId);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        Patient patient = this.patientService.getPatient(patientId);
        // 患者用户不存在
        if (patient == null) {
            LOGGER.error("patient case detail ERROR ; patient not exist. patientId {}, caseId {}", patientId, caseId);
            throw new BusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        // 患者被禁用
        if (patient.getAccountStatus() != 0) {
            LOGGER.error("patient case detail ERROR ; patient account status wrong. patientId {}, caseId {}", patientId, caseId);
            throw new BusinessException(ExceptionCodes.PATIENT_ACCOUNT_ERROR);
        }
        CaseDetailVO caseDetailVO = this.patientCaseFileService.getCaseDetail(patientId, caseId);
        // 成功获取患者病例信息，日志级别info
        LOGGER.info("patient case detail SUCCESS ; patientId {},caseId {}", patientId, caseId);
        return caseDetailVO;
    }

    /**
     * 保存病历档案 PatientCaseController.saveCaseFile()<BR> <P>Author : Amber </P>
     * <P>Date : 2015年9月13日 </P>
     *
     * @param patientId 患者id
     *                  密钥
     * @param data      病例实体
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ApiOperation(value = "保存病历档案", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> saveCaseFile(Long patientId, String data) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        // 参数异常
        if (patientId == null || StringUtils.isBlank(data) || !data.startsWith("[{") || !data.endsWith("}]")) {
            // 日志记录参数信息
            LOGGER.error("patient case save ERROR ; illegal param : patientId {},data {}", patientId, data);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        // 参数转换
        CaseDetailVO caseVO = ParamsUtil.getFirstParams(data, CaseDetailVO.class);
        // 取消备注必填限制。V1.4 @2015-11-14 by zhoupeipei
        if (caseVO == null || caseVO.getVistingTime() == null) {
            // 保存目标异常或必填项不全
            LOGGER.error("patient case save ERROR ; data missing required param : data {}", data);
            throw new BusinessException(ExceptionCodes.INVALID_REQUEST);
        }
        // 上传图片url不可为空
        if (!this.validateImgUrl(caseVO)) {
            LOGGER.error("patient case save ERROR ; data imgs imgUrl is null : data {}", data);
            throw new BusinessException(ExceptionCodes.INVALID_REQUEST);
        }
        // 上传图片必填上传时间
        if (!this.validateUploadtime(caseVO)) {
            LOGGER.error("patient case save ERROR ; data imgs uploadTime is null : data {}", data);
            throw new BusinessException(ExceptionCodes.CASE_IMG_UPLOADTIME_IS_NULL);
        }
        Patient patient = this.patientService.getPatient(patientId);
        // 患者用户不存在
        if (patient == null) {
            LOGGER.error("patient case save ERROR ; patient not exist. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        // 患者被禁用
        if (patient.getAccountStatus() != 0) {
            LOGGER.error("patient case save ERROR ; patient account status wrong. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_ACCOUNT_ERROR);
        }
        // 保存
        CaseDetailVO saveResult = this.patientCaseFileService.savePatientCaseFile(patient, caseVO);
        Map<String, Object> result = new HashMap<>();
        result.put("caseFile", saveResult);
        // 新用户，发红包
        // if (saveResult.getFirst()) {
        // patientAccountService.addIncome(patientId,
        // PatientConstant.GIFT_COMPLETE_CASEFILE,
        // PatientAccountHistory.INCOME_CAUSE_CASE_FILE,
        // patientId, "");
        // GiftRechargeVO giftRecharge = new GiftRechargeVO();
        // giftRecharge.setValue(PatientConstant.GIFT_COMPLETE_CASEFILE);
        // result.put("giftRecharge", giftRecharge);
        // }
        // 日志记录，级别info
        LOGGER.info("patient case save SUCCESS ; patientId {},data {}", patientId, data);
        return result;
    }

    /**
     * 更新病例档案图片（新增或删除） PatientCaseController.updateCaseImgs()<BR> <P>Author :
     * Gaoll </P> <P>Date : 2015年9月28日 </P>
     *
     * @param patientId
     * @param caseId
     * @param type
     * @param imgs      操作后需要保存的图片list
     *
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更新病例档案图片(新增或删除)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public CaseDetailVO updateCaseImgs(Long patientId, String caseId, Integer type, String imgs) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        // 参数校验
        if (patientId == null || StringUtils.isBlank(caseId) || type == null) {
            LOGGER.error("patient case update ERROR ; illegal param : patientId {},caseId {},type{}", patientId, caseId, type);
            throw new BusinessException(ExceptionCodes.INVALID_REQUEST);
        }
        // 图片类型校验
        if (PatientConstant.CASE_IMG_TYPE_ADVICE != type && PatientConstant.CASE_IMG_TYPE_PRESCRIPTION != type
                && PatientConstant.CASE_IMG_TYPE_CHECK != type) {
            LOGGER.error("patient case update ERROR ; illegal imgs type : patientId {},  caseId {}, type{}", patientId, caseId, type);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        // 参数转换
        List<CaseImgVO> imgsList = ParamsUtil.getJsonObjList(imgs, CaseImgVO.class);
        // 上传图片必填上传时间-上传url
        for (CaseImgVO tempImg : imgsList) {
            if (null != tempImg && null == tempImg.getUploadTime()) {
                LOGGER.error("patient case update ERROR ; imgs uploadTime is null : imgs {}", imgs);
                throw new BusinessException(ExceptionCodes.CASE_IMG_UPLOADTIME_IS_NULL);
            }
            if (null != tempImg && StringUtils.isEmpty(tempImg.getImgUrl())) {
                LOGGER.error("patient case update ERROR ; imgs imgUrl is null : imgs {}", imgs);
                throw new BusinessException(ExceptionCodes.PARAM_ERROR);
            }
        }
        Patient patient = this.patientService.getPatient(patientId);
        // 患者用户不存在
        if (patient == null) {
            LOGGER.error("patient case list ERROR ; patient not exist. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        // 患者被禁用
        if (patient.getAccountStatus() != 0) {
            LOGGER.error("patient case list ERROR ; patient account status wrong. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_ACCOUNT_ERROR);
        }
        this.patientCaseFileService.updateCaseImgs(patientId, caseId, type, imgsList);
        // 数据回显
        CaseDetailVO caseDetailVO = this.patientCaseFileService.getCaseDetail(patientId, caseId);
        LOGGER.info("patient case update SUCCESS 。patientId {},caseId {}, type{}", patientId, caseId, type);
        return caseDetailVO;
    }

    /**
     * 删除病历档案 PatientCaseController.deleteCaseFile()<BR> <P>Author : Amber </P>
     * <P>Date : 2015年9月14日 </P>
     *
     * @param patientId
     * @param caseId
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @ApiOperation(value = "删除病例档案", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public void deleteCaseFile(Long patientId, String caseId) throws BusinessException {
        if (null == patientId) {
            patientId = (Long) ResourceHolder.getResource(SettingConfig.PATIENT_ID);
        }
        // 参数校验
        if (patientId == null || StringUtils.isBlank(caseId)) {
            // 错误日志
            LOGGER.error("patient case delete ERROR ; illegal param : patientId {}, caseId {}", patientId, caseId);
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        Patient patient = this.patientService.getPatient(patientId);
        // 患者用户不存在
        if (patient == null) {
            LOGGER.error("patient case list ERROR ; patient not exist. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        // 患者被禁用
        if (patient.getAccountStatus() != 0) {
            LOGGER.error("patient case list ERROR ; patient account status wrong. patientId {}", patientId);
            throw new BusinessException(ExceptionCodes.PATIENT_ACCOUNT_ERROR);
        }
        this.patientCaseFileService.deleteCaseFile(patient, caseId);
        // 成功删除日志
        LOGGER.info("patient case delete SUCCESS ; patientId {},caseId {}", patientId, caseId);
    }

    /**
     * 校验图片上传url PatientCaseController.validateImgUrl()<BR> <P>Author : Gaoll
     * </P> <P>Date : 2015年9月29日 </P>
     *
     * @param caseVO
     *
     * @return
     */
    private boolean validateImgUrl(CaseDetailVO caseVO) {

        boolean passFlag = true;
        for (CaseImgVO tempImg : caseVO.getAdviceList()) {
            if (null != tempImg && StringUtils.isEmpty(tempImg.getImgUrl())) {
                passFlag = false;
            }
        }
        for (CaseImgVO tempImg : caseVO.getCheckList()) {
            if (null != tempImg && StringUtils.isEmpty(tempImg.getImgUrl())) {
                passFlag = false;
            }
        }
        for (CaseImgVO tempImg : caseVO.getPrescriptionList()) {
            if (null != tempImg && StringUtils.isEmpty(tempImg.getImgUrl())) {
                passFlag = false;
            }
        }
        return passFlag;
    }

    /**
     * 校验图片上传时间是否通过 PatientCaseController.validateUploadtime()<BR> <P>Author :
     * Gaoll </P> <P>Date : 2015年9月23日 </P>
     *
     * @param caseVO
     *
     * @return
     */
    private boolean validateUploadtime(CaseDetailVO caseVO) {

        boolean passFlag = true;
        for (CaseImgVO tempImg : caseVO.getAdviceList()) {
            if (null != tempImg && null == tempImg.getUploadTime()) {
                passFlag = false;
            }
        }
        for (CaseImgVO tempImg : caseVO.getCheckList()) {
            if (null != tempImg && null == tempImg.getUploadTime()) {
                passFlag = false;
            }
        }
        for (CaseImgVO tempImg : caseVO.getPrescriptionList()) {
            if (null != tempImg && null == tempImg.getUploadTime()) {
                passFlag = false;
            }
        }
        return passFlag;
    }

}
